package com.example.demo.encrypt;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;
//import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * @program: mpf-mod-openapi-service
 * @description:
 * @author: zt22328 赵儒定
 * @create: 2022-07-07 16:04
 **/
@NoArgsConstructor
//@AllArgsConstructor
public class DecryptSerializer extends JsonSerializer<String> implements ContextualSerializer {

    public static String key;

    @SneakyThrows
    @Override
    public void serialize(String origin, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (StringUtils.isEmpty(origin)) {
            gen.writeString(AESUtil.encrypt(origin,key));
            return;
        }
        gen.writeString(origin);
    }


    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
                Decrypt privacyEncrypt = beanProperty.getAnnotation(Decrypt.class);
                if (privacyEncrypt == null) {
                    privacyEncrypt = beanProperty.getContextAnnotation(Decrypt.class);
                }
                if (privacyEncrypt != null) {
                    return new DecryptSerializer();
                }
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(null);
    }
}
